package study;
import java.util.Arrays;

public class code_RedBlueStone {

    public static int redBlueStone(int[][] arr) {
        int N = arr.length;
        if (N % 2 != 0) {
            return -1;
        }
        int redCost = 0;
        int redNum = 0;
        int blueNum = 0;
        // 按红蓝绝对值大小进行 数组排序
        Arrays.sort(arr, (a, b) -> a[0] == 0 && b[0] == 0 ? (b[1] - b[2] - a[1] + a[2]) : (a[0] - b[0]));
        for (int i = 0; i < N; i++) {
            redNum += arr[i][0] == 1 ? 1 : 0;
            blueNum += arr[i][0] == 2 ? 1 : 0;
            if (arr[i][0] == 0) {
                redCost += arr[i][1];
            }
        }

        if (redNum > N >> 1 || blueNum > N >> 1) {
            return -1;
        }

        // blueNum = zero - ((N >> 1) - redNum);
        for (int i = 0; i < (N >> 1) - blueNum; i++) {
            redCost += arr[i][2] - arr[i][1];
        }

        return redCost;
    }

    public static int minCost(int[][] stones) {
        int n = stones.length;
        if ((n & 1) != 0) {
            return -1;
        }
        // 排序
        Arrays.sort(stones, (a, b) -> a[0] == 0 && b[0] == 0 ? (b[1] - b[2] - a[1] + a[2]) : (a[0] - b[0]));
        int zero = 0;
        int red = 0;
        int blue = 0;
        int cost = 0;
        for (int i = 0; i < n; i++) {
            if (stones[i][0] == 0) {
                zero++;
                cost += stones[i][1];
            } else if (stones[i][0] == 1) {
                red++;
            } else {
                blue++;
            }
        }
        if (red > (n >> 1) || blue > (n >> 1)) {
            return -1;
        }
        blue = zero - ((n >> 1) - red);
        for (int i = 0; i < blue; i++) {
            cost += stones[i][2] - stones[i][1];
        }
        return cost;
    }

    public static void main(String[] args) {
        int[][] stones = { { 1, 5, 3 }, { 2, 7, 9 }, { 0, 6, 4 },
                { 0, 7, 9 }, { 0, 2, 1 }, { 0, 5, 9 } };
        System.out.println("minCost(stones):" + minCost(stones));
        System.out.println("red:" + redBlueStone(stones));

        int[][] rest2 = {
                { 1, 2, 3 }, { 0, 4, 3 }, { 0, 6, 3 }, { 0, 6, 8 },
                { 0, 6, 12 }, { 0, 6, 1 }, { 2, 2, 3 }, { 1, 2, 3 }
        };

        System.out.println("minCost(stones):" + minCost(rest2));
        System.out.println("red" + redBlueStone(rest2));
    }
}
